<template>
  <div id="container">
    <div class="header">
      <headerTou :headerTitle="headerTitle"></headerTou>
      <!-- <div class="tabs">
          <div @click="tabs" v-if="showtabs && user.roleName != 'UNIT_ADMIN'">
            切换<i class="el-icon-caret-right"></i>
          </div>
          <div @click="fanhui" v-if="!showtabs">
            <i class="el-icon-caret-left"></i>返回
          </div>
          <img :src="user.dataVLogo ? user.dataVLogo : ''" class="logo" />
        </div> -->
      <div class="header_left">
        <div class="time">{{ timing }}</div>
      </div>
      <div class="header_right">
        <el-tooltip
          class="item"
          effect="dark"
          :content="fullScreenContent"
          placement="bottom"
        >
          <i :class="quanping1" @click="onFullScreen"></i>
        </el-tooltip>
        <el-tooltip
          class="item"
          effect="dark"
          content="后台系统"
          placement="bottom"
        >
          <i
            class="iconfont houtai-xitongguanli tableBtnIcon"
            @click="onHoutai"
          ></i>
        </el-tooltip>
        <el-tooltip
          class="item"
          effect="dark"
          content="退出"
          placement="bottom"
        >
          <i class="iconfont tuichu1 tableBtnIcon" @click="exit"></i>
        </el-tooltip>
      </div>
    </div>

    <!-- 单位详情 -->
    <div class="left">
      <div class="left_zero">
        <div class="zero_one boxall">
          <div class="tit01 cut" @click="onCut">
            <span>消控室信息</span>
            <i class="iconfont xiangyoujiantou"></i>
          </div>
          <leftTop class="insideall" :fcInfo="fcInfo"></leftTop>
          <div class="boxfoot"></div>
        </div>
        <div class="zero_two boxall">
          <div class="tit01">值班人员</div>
          <leftMiddle class="insideall" :userIds="userIds"></leftMiddle>
          <div class="boxfoot"></div>
        </div>
      </div>
      <div class="left_one boxall">
        <div class="tit01 tit02">
          <span>状态监控</span>
          <img
            src="../../../assets/images/datav/record.png"
            class="bar-history"
            @click="onRecord"
          />
        </div>
        <div class="boxfoot">
          <condition
            ref="refcondition"
            :fcInfo="fcInfo"
            :b_panic="b_panic"
            :deviceCode="deviceCode_c"
            :Info_mqtt="Info_mqtt"
          ></condition>
        </div>
      </div>
      <div class="left_two boxall">
        <div class="tit01 tit02">
          <span>消控室监控</span>
          <!-- <el-tooltip
              class="item"
              effect="dark"
              content="监控列表"
              placement="bottom"
            >
              <el-button class="el_button" @click="gridding"
                ><i class="iconfont dasuolvetuliebiao"></i
              ></el-button>
            </el-tooltip> -->
        </div>
        <monitoring
          ref="refmonitoring"
          class="video_box"
          :frontDeviceRelatedVO2="frontDeviceRelatedVO2"
        ></monitoring>
        <div class="boxfoot"></div>
      </div>
    </div>

    <!-- 右侧 -->
    <div class="right">
      <div class="right_div boxall fc-loading">
        <div class="tit01">多线盘</div>
        <bottomLeft
          class="insideall"
          ref="refbottomLeft"
          :ml_reel="ml_reel"
          :Info_mqtt="Info_mqtt"
          v-loading="v_loading_left"
        ></bottomLeft>
        <div class="boxfoot"></div>
      </div>
      <div class="right_alarm boxall fc-loading">
        <div class="tit01">总线盘</div>
        <bottomRight
          class="insideall"
          ref="refbottomRight"
          :b_disk="b_disk"
          :Info_mqtt="Info_mqtt"
          v-loading="v_loading_right"
        ></bottomRight>
        <div class="boxfoot"></div>
      </div>
    </div>

    <div class="shade" v-if="showShade"></div>
    <transition name="fade" mode="out-in">
      <switchPassword
        class="frame"
        ref="refswitchPassword"
        :statusInfo="statusInfo"
        :commandInfo="commandInfo"
        @update="switchUpdate"
      ></switchPassword>
    </transition>

    <transition>
      <record
        class="frame"
        ref="refrecord"
        :fcInfo="fcInfo"
        :deviceCode="deviceCode_c"
      ></record>
    </transition>

    <transition>
      <alarmEetails
        class="frame"
        ref="refalarmDetails"
        :detailsInfo="detailsInfo"
        :detailsName="detailsName"
        :fcInfo="fcInfo"
        :userIds="userIds"
      ></alarmEetails>
    </transition>
    <transition name="fade" mode="out-in">
      <cutHost
        class="frame"
        ref="refCutHost"
        :isEmpty="isEmpty"
        :fcId="fcInfo.id"
        :hiId="
          JSON.stringify(c_hostInfo) == '{}'
            ? deviceCode_c
            : c_hostInfo.deviceCode
        "
        @update="cutHostUpdate"
      ></cutHost>
    </transition>

    <transition>
      <command
        class="frame"
        ref="refcommand"
        :commandInfo="commandInfo"
        :deviceCode_c="deviceCode_c"
      ></command>
    </transition>
    <transition>
      <setHostNumber
        class="frame"
        ref="refsetHostNumber"
        :deviceCode_c="deviceCode_c"
        @update="getDetectorDxtend"
      >
      </setHostNumber>
    </transition>

    <transition>
      <deviceInfo
        class="frame"
        ref="refdeviceInfo"
        :deviceList="deviceList"
      ></deviceInfo>
    </transition>
    <transition>
      <relevancy class="frame" ref="refrelevancy" :fcInfo="fcInfo"></relevancy>
    </transition>

    <transition>
      <binding
        class="frame"
        ref="refbinding"
        :bindingName="bindingName"
        :bindingState="bindingState"
        :cameraCode="cameraCode"
        :deviceList="deviceList"
      ></binding>
    </transition>

    <transition>
      <surveillanceVideo
        class="frame"
        ref="refsurveillanceVideo"
        :deviceList="deviceList"
      ></surveillanceVideo>
    </transition>
  </div>
</template>
  
  <script>
import headerTou from "./components/headerTou.vue"; //头部组件
import { reqOrg, reqLogout, reqClient } from "@api/apiDatav.js";
import {
  reqFireControlRoomDetail,
  reqKeyCommandList,
  reqDetectorDxtend,
  reqKeyCommandSend,
  reqDetectorDetail,
  reqFireControlRoomPage,
} from "@api/api.js";
import { mapState, mapMutations } from "vuex";
import screenfull from "screenfull"; //全屏
import { onDestory } from "@utils/map/map";
import condition from "./components/condition.vue";
import monitoring from "./components/monitoring.vue";
import bottomLeft from "./components/bottomLeft.vue";
import bottomRight from "./components/bottomRight.vue";
import leftTop from "./components/leftTop.vue";
import leftMiddle from "./components/leftMiddle.vue";
import switchPassword from "./components/switchPassword.vue";
import record from "./components/record.vue";
import alarmEetails from "./components/alarmEetails.vue";
import cutHost from "./components/cutHost.vue";
import command from "./components/command.vue";
import setHostNumber from "./components/setHostNumber.vue";
import deviceInfo from "./components/deviceInfo.vue";
import relevancy from "./components/relevancy.vue";
import binding from "./components/binding.vue";
import surveillanceVideo from "./components/surveillanceVideo.vue";

import mqtt from "mqtt"; //index.html引入的已弃用

export default {
  name: "datav",
  components: {
    headerTou,
    condition,
    monitoring,
    bottomLeft,
    bottomRight,
    leftTop,
    leftMiddle,
    switchPassword,
    command,
    record,
    alarmEetails,
    // Frame,
    cutHost,
    setHostNumber,
    deviceInfo,
    relevancy,
    binding,
    surveillanceVideo,
  },
  data() {
    return {
      fullScreenContent: "全屏",
      quanping1: "iconfont pc-quanping tableBtnIcon",
      xitong: require("@assets/images/datav/xitong.png"),
      tuichu: require("@assets/images/datav/tuichu.png"),
      jiankon: require("@assets/images/datav/jiankon.png"),
      zhuji: require("@assets/images/datav/zhuji.png"),
      drawer: false,
      defaultProps: {
        children: "children",
        flatType: "flatType",
        label: "orgName",
      },
      RegionProps: {
        children: "children",
        isLeaf: "hasChildren",
        label: "regionName",
      },
      formInline: {
        orgName: "",
      },
      dataList: [],
      Regionlist: [],
      Regionlisttwo: [],
      showorg: true, //组织|行政区域切换
      orgflag: false, //控制单位|租户页面展示
      showtabs: true, //控制切换按钮
      addInfo: {
        provinceCode: "",
        cityCode: "",
        areaCode: "",
        streetCode: "",
        communityCode: "",
      },
      provinceList: [], //省
      cityList: [], //市
      areaList: [], //区
      streetList: [], //街道
      communityList: [], //社区
      timerval: null,
      logo: require("@assets/images/logo4.png"),
      timing: "",
      timer: null,
      fcInfo: {},
      deviceList: [],
      deviceCode_c: "",
      b_panic: [], // 基本面板
      ml_reel: [], // 多線盤
      b_disk: [], // 總線盤
      statusInfo: {},
      commandInfo: {},
      headerTitle: "",
      userIds: [],
      showShade: false,
      detailsInfo: {},
      detailsName: "",
      frontDeviceRelatedVO: [],
      frontDeviceRelatedVO2: [],
      c_fcInfo: {},
      c_hostInfo: {},
      isEmpty: false,
      protocol: "",
      v_loading_left: false,
      v_loading_right: false,
      audio: new Audio(),

      // mqtt
      instanceId: "post-cn-7mz2d28ne0e", //实例 ID
      host: "post-cn-7mz2d28ne0e.mqtt.aliyuncs.com",
      port: 443, //WebSocket 协议服务端口，如果是走 HTTPS，设置443端口   ||80
      // topic: `alarm/${this.user.userId}`, //需要操作的 Topic,第一级父级 topic
      topic: `alarm/${this.$store.state.user.userId}`, //需要操作的 Topic,第一级父级 topic
      useTLS: true, //是否走加密 HTTPS，如果走 HTTPS，设置为 true
      cleansession: true,
      clientId: this.$store.state.datav.clientId || "", //GroupId@@@DeviceId，由 Group ID 和自己指定的 Device ID 组合构成
      mqtt: {},
      client: {},
      message: "",
      reconnectTimeout: 2000,
      username: this.$store.state.datav.mu || "",
      password: this.$store.state.datav.mp || "",
      isConnect: false, // 连接中断
      failConnect: false, // 连接失败
      Info_mqtt: {},

      bindingState: "",
      bindingName: "",
      cameraCode: "",
      deviceStr: {},
    };
  },
  computed: {
    ...mapState(["user", "datav", "config", "spacesManage"]),
  },
  watch: {
    cursorGrab(val) {
      this.cursor = val;
    },
  },
  beforeDestroy() {
    clearTimeout(this.timer); //页面销毁前，清除延时器
    clearTimeout(this.timerval); //页面销毁前，清除延时器
    this.timer_loading && clearTimeout(this.timer_loading);
  },
  destroyed() {
    this.client.end();
  },
  async mounted() {
    this.onTiming();
    if (this.$route.query && JSON.stringify(this.$route.query) !== "{}") {
      this.isEmpty = false;
      this.c_fcInfo = {};
      this.c_hostInfo = {};
      this.fcInfo = this.$route.query; // 消控室信息
      this.getDataList();
      this.getFireControlRoomDetail();
    } else {
      // console.log(222222222);
      await this.getDataList();
      await this.getFireControlRoomDetail(true);
      // this.isEmpty = true;
      // this.showShade = true;
      // this.$refs.refCutHost.dialogVisible = true;
    }
    // console.log(this.fcInfo, "this.fcInfo222222");
    this.initMqtt();
  },
  methods: {
    ...mapMutations([
      "saveorgarr",
      "saveIsWhiteTheme",
      "saveflagDatav",
      "saveOrgInfo",
    ]),
    // 获取列表
    async getDataList() {
      const res = await reqFireControlRoomPage(1, 10, {
        tenantId: this.user.tenantId,
        userId: this.user.userId,
        roleName: this.user.roleName,
        orgId: this.c_orgId ? this.c_orgId : "", //机构||单位
        name: "",
      });
      if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
      let { rows, total } = res.data;
      // rows.forEach((item) => {
      //   if (item.fcrDeviceRelateds.length) {
      //     item.fcrDeviceRelateds.forEach((item2) => {
      //       if (
      //         // UserTransferDevice用户传输装置  FireAlarmController火灾报警控制器
      //         item2.deviceType === "UserTransferDevice" ||
      //         item2.deviceType === "FireAlarmController"
      //       ) {
      //         this.fcInfo = this.c_fcInfo = item;
      //         this.c_hostInfo = item2;
      //       }
      //     });
      //   }
      // });
      for (let i = 0; i < rows.length; i++) {
        if (rows[i].fcrDeviceRelateds.length) {
          for (let j = 0; j < rows[i].fcrDeviceRelateds.length; j++) {
            if (
              rows[i].fcrDeviceRelateds[j].deviceType ===
                "UserTransferDevice" ||
              rows[i].fcrDeviceRelateds[j].deviceType === "FireAlarmController"
            ) {
              this.fcInfo = this.c_fcInfo = rows[i];
              this.c_hostInfo = rows[i].fcrDeviceRelateds[j];
              // this.$store.commit("saveDeviceCode", this.c_hostInfo.deviceCode);
              break; // 跳出内层循环
            }
          }
          if (JSON.stringify(this.fcInfo) != "{}") {
            break; // 如果已经找到满足条件的项，跳出外层循环
          }
        }
      }
    },
    // 切换设备
    onCut() {
      this.isEmpty = false;
      this.showShade = true;
      this.$refs.refCutHost.dialogVisible = true;
    },
    // 获取详情
    async getFireControlRoomDetail(bl = false) {
      console.log("获取详情");
      const res = await reqFireControlRoomDetail(
        bl ? this.c_fcInfo.id : this.fcInfo.id
      );
      if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
      const {
        fcrDutyUserRelatedVO,
        frontDeviceRelatedVO,
        buildingId,
        buildingName,
        floorId,
        floorName,
        spaceId,
        spaceName,
        name,
      } = res.data.info;
      this.headerTitle = name;
      // 值班人员
      if (fcrDutyUserRelatedVO && fcrDutyUserRelatedVO.length > 0) {
        this.userIds = JSON.parse(JSON.stringify(fcrDutyUserRelatedVO));
      }
      // 设备
      if (bl) {
        this.deviceCode_c = this.c_hostInfo.deviceCode;
        this.getKeyCommandList();
        this.getDetectorDxtend();
      } else {
        if (frontDeviceRelatedVO && frontDeviceRelatedVO.length > 0) {
          frontDeviceRelatedVO.forEach((item) => {
            item.imei = item.deviceCode;
            item.productName = item.deviceName;
            if (
              item.deviceType === "UserTransferDevice" ||
              item.deviceType === "FireAlarmController"
            ) {
              this.deviceCode_c = item.deviceCode;
            }
          });
          this.getKeyCommandList();
          this.getDetectorDxtend();
        }
      }
      this.frontDeviceRelatedVO2 = [];
      if (frontDeviceRelatedVO && frontDeviceRelatedVO.length > 0) {
        frontDeviceRelatedVO.forEach((item) => {
          item.imei = item.deviceCode;
          item.productName = item.deviceName;
          if (item.deviceType === "Camera") {
            this.frontDeviceRelatedVO2.push(item);
          }
          if (
            item.imei == this.c_hostInfo.deviceCode ||
            this.deviceCode_c == item.imei
          ) {
            if (!this.$store.state.fire.fireDeviceCode) {
              this.$store.commit("saveDeviceCode", item.imei);
            }

            this.protocol = item.protocol;
          }
        });
        this.$nextTick(() => {
          this.$refs.refmonitoring.gettoken(); //消控室监控
        });
      }
      this.$nextTick(() => {
        this.$refs.refcondition.getData(); //状态监控
      });
    },
    // 获取指令列表
    async getKeyCommandList() {
      let res = await reqKeyCommandList({
        deviceCode: this.deviceCode_c,
      });
      if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
      let { list } = res.data;
      this.b_panic = [];
      this.ml_reel = [];
      this.b_disk = [];
      let b_panic = []; // 基本面板
      let ml_reel = []; // 多線盤
      let b_disk = []; // 總線盤
      list.forEach((item, index) => {
        if (item.layoutType == 1) {
          b_panic.push(item);
        } else if (item.layoutType == 2) {
          ml_reel.push(item);
        } else if (item.layoutType == 3) {
          b_disk.push(item);
        }

        if (index == list.length - 1) {
          this.b_panic = b_panic;
          this.ml_reel = ml_reel;
          this.b_disk = b_disk;
        }
      });
      console.log(this.b_panic, "b_panic");
    },

    // 状态信息
    async getDetectorDxtend() {
      let res = await reqDetectorDxtend({
        deviceCode: this.deviceCode_c,
      });
      if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
      this.statusInfo = res.data.detail;
    },

    // 多线盘/總線盤的開關
    onSwitch(data) {
      this.commandInfo = data;
      this.deviceCode_c = data.deviceCode;
      this.getDetectorDxtend();
      this.showShade = true;
      this.$refs.refswitchPassword.dialogVisible = true;
    },
    onRecord(data) {
      this.showShade = true;
      this.$refs.refrecord.dialogVisible = true;
    },
    // 停止铃声
    pauseAudio() {
      this.audio.src = "";
      this.audio.pause();
    },
    // 播放铃声
    playAudio() {
      // this.audio.src =
      //   "https://gelivideo.oss-cn-shenzhen.aliyuncs.com/alarm.mp3";
         this.audio.src = require("@/assets/audio/sound.mp3");
      this.audio.loop = true; //循环播放
      this.audio.play();
    },
    onEetails(data, name, flag = false) {
      // console.log(data, "data");
      this.detailsInfo = data;
      this.detailsName = name;
      if (name == "反馈1") return; //监听到反馈不弹窗，只更新列表
      if (flag) {
        this.playAudio();
      }
      this.showShade = true;
      if (this.$refs.refalarmDetails.dialogVisible) return;
      this.$refs.refalarmDetails.dialogVisible = true;
    },
    //更新告警列表
    AlarmHandleResult() {
      this.$refs.refcondition.getAlarmList();
    },
    //更新故障列表
    getHiddenDangerList() {
      this.$refs.refcondition.getHiddenDangerList();
    },
    // 下发指令
    async onCommand(item) {
      if (this.protocol == 7 && !this.statusInfo.hostNumber) {
        this.$modal.notifyWarning("请先设置主机号");
        setTimeout(() => {
          this.showShade = true;
          this.$refs.refsetHostNumber.dialogVisible = true;
        }, 500);
        return;
      }
      if (item.layoutType == 1) {
        this.commandInfo = item;
        this.showShade = true;
        this.$refs.refcommand.dialogVisible = true;
        // const result = await this.$confirm(
        //   `此操作将下发 ${item.keyName} 指令, 是否继续?`,
        //   "提示",
        //   {
        //     confirmButtonText: "确定",
        //     cancelButtonText: "取消",
        //     type: "warning",
        //   }
        // ).catch(() => {});
        // if (result !== "confirm") return;
        // this.keyCommandSendFoo(item);
      } else {
        // this.commandInfo = JSON.parse(JSON.stringify(item));
        // this.$refs.refInstructPassword.dialogVisible = true;
      }
    },
    // 设备详情
    async getDevice(item) {
      // console.log(item,1123);
      this.deviceStr = item;
      if (!item.detectorDeviceCode)
        return this.$modal.notifyWarning("请先配置探测器");
      this.getDetectorDetail(); // 探测器详情
      this.showShade = true;
      this.$refs.refdeviceInfo.dialogVisible = true;
    },
    // 探测器详情
    async getDetectorDetail() {
      let res = await reqDetectorDetail({
        deviceCode: this.deviceStr.deviceCode,
        detectorCode: this.deviceStr.detectorDeviceCode,
      });
      if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
      this.deviceList = res.data.detail;
    },
    // 关联设备
    getrelevancy() {
      if (this.deviceList.cameraStatus == 0) {
        this.$refs.refrelevancy.dialogVisible = true;
      } else {
        this.$refs.refsurveillanceVideo.dialogVisible = true;
      }
    },
    // 绑定 拆除
    getBinding(name, bindingState, item) {
      this.bindingName = name;
      this.bindingState = bindingState;
      if (bindingState == "1") {
        this.cameraCode = item.imei; //摄像机编码
      }
      this.$refs.refbinding.dialogVisible = true;
    },
    async closeBinding(flag = true) {
      if (flag) {
        this.$refs.refrelevancy.dialogVisible = false;
      }
      this.getDetectorDetail(); // 更新探测器详情
    },

    async keyCommandSendFoo(item) {
      let res = await reqKeyCommandSend({
        deviceCode: this.deviceCode_c,
        id: item.id,
      });
      if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
      this.$modal.notifySuccess("指令下发成功");
      // setTimeout(() => {
      //   this.getDetectorDxtend();
      //   this.getKeyCommandList();
      // }, 3000);
    },
    // 启停
    switchUpdate(type) {
      // 已启用ws 此块代码暂作废
      if (type == "submit") {
        // if (this.commandInfo.layoutType == 2) {
        //   this.v_loading_left = true;
        //   this.$refs.refbottomLeft.onCloseFeedback(this.commandInfo);
        // } else if (this.commandInfo.layoutType == 3) {
        //   this.v_loading_right = true;
        //   this.$refs.refbottomRight.onCloseFeedback(this.commandInfo);
        // }
        // this.timer_loading && clearTimeout(this.timer_loading);
        // this.timer_loading = setTimeout(async () => {
        //   await this.getKeyCommandList();
        //   this.v_loading_left = false;
        //   this.v_loading_right = false;
        // }, 3000);
      } else {
        // this.getKeyCommandList();
        if (this.commandInfo.layoutType == 2) {
          this.$refs.refbottomLeft.onChangeSwitch(this.commandInfo);
        } else if (this.commandInfo.layoutType == 3) {
          this.$refs.refbottomRight.onChangeSwitch(this.commandInfo);
        }
      }
    },
    // 消控室选择
    cutHostUpdate(data) {
      this.fcInfo = this.c_fcInfo = data.fcInfo;
      this.c_hostInfo = data.hostInfo;
      console.log(" this.c_hostInfo111111", this.c_hostInfo);
      this.$store.commit("saveDeviceCode", this.c_hostInfo.deviceCode);
      this.getFireControlRoomDetail(true);
    },
    // 计时器
    onTiming() {
      let _this = this;
      _this.timer && clearTimeout(_this.timer); //清除定时器
      _this.timer = setTimeout(time, 1000); //開始运行
      function time() {
        _this.timer && clearTimeout(_this.timer); //清除定时器
        let dt = new Date();
        let y = dt.getFullYear();
        let mt = dt.getMonth() + 1;
        let day = dt.getDate();
        let h = dt.getHours(); //获取时
        let m = dt.getMinutes(); //获取分
        let s = dt.getSeconds(); //获取秒
        _this.timing =
          y +
          "/" +
          Appendzero(mt) +
          "/" +
          Appendzero(day) +
          " " +
          Appendzero(h) +
          ":" +
          Appendzero(m) +
          ":" +
          Appendzero(s) +
          "";
        function Appendzero(obj) {
          if (obj < 10) return "0" + "" + obj;
          else return obj;
        }
        _this.timer = setTimeout(time, 1000); //设定定时器，循环运行
      }
    },
    onMainframe() {
      this.$router.push("/mainframe");
    },
    onVideo() {
      this.saveOrgInfo({});
      this.$router.push("/video/surveillance");
    },
    // // 获取mqtt信息
    // async getMqttInfo() {
    //   let res = await reqClient(this.user.userId);
    //   if (res.code !== 20000) return this.$message.error(res.message);
    //   this.$store.commit("saveMu", res.data.rows.mu);
    //   this.$store.commit("saveMp", res.data.rows.mp);
    //   this.$store.commit("saveId", res.data.rows.mc);
    // },
    // 行政区域确认按钮
    regionSubmit(data) {
      this.Regionlisttwo = data;
      // console.log(this.Regionlisttwo);
      this.drawer = false;
      this.$refs.refmidmap.getOrg2(this.Regionlisttwo); //切换地图单位列表信息
    },

    // 行政区域重置单位
    regionClose(data) {
      // this.getOrgList();
      this.Regionlisttwo = data;
      this.drawer = false;
      this.$refs.refmidmap.getOrg(); //地图单位列表
    },
    // 查询
    searchClick() {
      this.getOrg(true);
    },
    // 单位列表
    async getOrgList() {
      // 组织
      let res = await reqOrg({
        tenantId: this.user.tenantId,
        userId: this.user.userId,
        roleName: this.user.roleName,
        regionCode: "",
        regionLevel: 1,
        orgId: this.spacesManage.organizationInfo.orgId,
      });
      let rows = res.data.row;
      rows.forEach((item) => {
        item.regionName = item.orgName;
      });
      this.Regionlisttwo = rows;
    },
    // 组织|行政区域
    orgtabs(e) {
      if (e == 1) {
        this.showorg = true;
      } else {
        this.showorg = false;
      }
    },
    // 展示弹窗
    tabs() {
      this.drawer = true;
      this.$nextTick(() => {
        this.getOrg(true); //单位列表
        this.$refs.refOrgFilter.getRegion();
      });
    },
    // 回到租户
    fanhui() {
      this.Regionlisttwo = [];
      this.addInfo = {
        provinceCode: "",
        cityCode: "",
        areaCode: "",
        streetCode: "",
        communityCode: "",
      };
      this.cityList = []; //市
      this.areaList = []; //区
      this.streetList = []; //街道
      this.communityList = []; //社区
      this.getOrgList();

      this.orgflag = true;
      this.showtabs = true;
      this.saveorgarr({}); // 存储单位详情
      this.$nextTick(async () => {
        this.$refs.refmidmap.getOrg(); //地图单位列表
        this.$refs.refequipment.DeviceType();
        this.$refs.refleftFour.AlarmType();
        this.$refs.refmidNoe.getDeviceCount();
        this.$refs.refmidNoe.getTodayAlarmCount();
        this.$refs.refmidTwo.getAlarmTotal();
        this.$refs.refmidTwo.getTodayAlarmCount();
        this.$refs.refmidTwo.getHandlingStatusCount();
        this.$refs.refright.AlarmList(); //告警默认请求十条
        this.$refs.refleftNoe.getOrgDevice();
        this.$refs.reforgSevenDays.getDispose(); //近七天告警趋势 清空
      });
    },
    closedrawer() {
      this.drawer = false;
    },
    // 组织机构
    toggleOrg(e) {
      let flag = false;
      if (e.id == this.datav.orgarr.id) {
        flag = true; //切换相同的单位不执行
      }
      this.saveorgarr(e); // 存储单位详情
      this.orgflag = false;
      this.$nextTick(async () => {
        this.$refs.refmidmap.getSpaceByOrgId(false, flag); //地图建筑物列表
        this.$refs.refright.AlarmList(); //告警默认请求十条
        this.$refs.reforgDevice.getDeviceCount(); //单位设备统计
        this.$refs.reforgReport.getAlarmTotal(); //单位告警统计
        this.$refs.reforgReport.getTodayAlarmCount(); //单位告警统计
        this.$refs.reforgReport.getHandlingStatusCount(); //单位告警统计
        this.$refs.reforgClassify.DeviceType(true); //单位设备分类
        this.$refs.reforgSevenDays.getSevenDayAlarm(); //单位七天告警
        // await this.$refs.reforgSevenDays.getCahrt()//单位七天告警
      });
      this.drawer = false;
      // if (this.user.roleName == 'TENANT_ADMIN') {
      this.showtabs = false;
      // }
    },
    // 行政区域
    toggleRegion(e) {
      let flag = false;
      if (e.id == this.datav.orgarr.id) {
        flag = true; //切换相同的单位不执行
      }
      if (e.id) {
        this.saveorgarr(e); // 存储单位详情
        this.orgflag = false;
        this.$nextTick(async () => {
          this.$refs.refmidmap.getSpaceByOrgId(false, flag); //地图建筑物列表
          this.$refs.reforgDevice.getDeviceCount(); //单位设备统计
          this.$refs.reforgReport.getAlarmTotal(); //单位告警统计
          this.$refs.reforgReport.getTodayAlarmCount(); //单位告警统计
          this.$refs.reforgReport.getHandlingStatusCount(); //单位告警统计
          this.$refs.reforgClassify.DeviceType(true); //单位设备分类
          this.$refs.refright.AlarmList(); //告警默认请求十条
          this.$refs.reforgSevenDays.getSevenDayAlarm(); //单位七天告警
          // await this.$refs.reforgSevenDays.getCahrt()//单位七天告警
        });
        this.drawer = false;
        // if (this.user.roleName == 'TENANT_ADMIN') {
        this.showtabs = false;
        // }
      }
    },
    //单位列表
    async getOrg(init = false, init2 = false) {
      let res = await reqOrg({
        tenantId: this.user.tenantId,
        userId: this.user.userId,
        roleName: this.user.roleName,
        regionCode: "",
        orgName: this.formInline.orgName,
      });
      if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
      this.dataList = res.data.row;
      if (init2) {
        let rows = res.data.row;
        rows.forEach((item) => {
          item.regionName = item.orgName;
        });
        this.Regionlisttwo = rows;
      }
      if (!init) {
        this.saveorgarr(res.data.row[0]); // 存储单位详情 第一次默认第一个单位详情
      }
    },
    //后台系统
    onHoutai() {
      this.saveIsWhiteTheme(false);
      // this.config.flagDatav=!this.config.flagDatav
      // this.$router.replace("/org/list")
      if (
        this.user.roleName == "INSTERALL_USER" ||
        this.user.roleName == "UNIT_ADMIN"
      ) {
        this.$router.replace("/org/list");
      } else {
        this.$router.replace("/fire/controlRoom");
      }
      this.$refs.refmonitoring.destroy(); //销毁摄像机
    },
    // 全屏
    onFullScreen() {
      if (screenfull.element == null) {
        this.fullScreenContent = "退出全屏";
        this.quanping1 = "iconfont compress tableBtnIcon";
      } else {
        this.fullScreenContent = "全屏";
        this.quanping1 = "iconfont pc-quanping tableBtnIcon";
      }
      screenfull.toggle();
    },

    // mqtt
    async initMqtt() {
      if (process.env.NODE_ENV == "development") {
        this.port = 80;
        // this.topic = `device/E622H52200030/${this.user.userId}`;
        this.connectUrl = `ws://${this.host}:${this.port}/mqtt/ws`;
        // this.connectUrl = `ws://192.168.1.14:1318/mqtt/ws`;
        this.useTLS = false;
      } else {
        this.port = 443;
        this.connectUrl = `wss://${this.host}:${this.port}/mqtt/wss`;
        this.useTLS = true;
      }

      await this.getMqttInfo(); // 获取mqtt信息
      this.clientId = this.datav.clientId;
      this.username = this.datav.mu;
      this.password = this.datav.mp;
      await this.MQTTconnect();
    },
    // MQTT中断函数    中断连接
    disconnect() {
      // console.log("中断连接");
      this.mqtt.disconnect(); //进行连接中断
    },
    // 监听连接断开时的状态
    onConnectionLost: function (response) {
      // console.log("监听连接断开时的状态");
      this.isConnect = false;
      this.failConnect = false;
    },
    // 连接
    MQTTconnect() {
      let _this = this;
      // this.onMessageArrived; //连接收到消息
      _this.client = mqtt.connect(_this.connectUrl, {
        clean: true,
        connectTimeout: 4000,
        reconnectPeriod: 1000,
        clientId: _this.clientId,
        username: _this.username,
        password: _this.password,
      });
      this.onConnect(); // 连接
      this.onReceive(); // 接受消息
    },
    // 监听连接
    onConnect() {
      this.client.on("connect", () => {
        console.log("已经连接成功");
        this.isConnect = true;
        let sendMsg = JSON.stringify("hello world");
        this.client.subscribe(this.topic, {
          qos: 0,
        }); //订阅
        this.message = this.client.publish(this.topic, sendMsg);
        this.message.destinationName = this.topic; // set topic
      });
    },
    // 监听接受消息
    onReceive() {
      this.client.on("message", async (topic, message, packet) => {
        let json = this.onTransJson(message); // 字节流转json
        if (json.indexOf("hello") > -1) return;
        var msg = JSON.parse(json);
        console.log("接收到消息msg", msg);
        this.isConnect = true; //如果接收到信息一定是在连接状态

        const dataType = msg.dataType;
        let info = msg.dataContent.chatMsg.msg;
        info.createTime = this.timestampToTime2(
          info.createTime // 时间戳转换
        );
        info.dataType = dataType;
        console.log(info, "info");
        //  console.log(this.deviceCode_c, "deviceCode_c");
        if (dataType == 1) {
          // 告警
          if (info.imei != this.deviceCode_c) return;
          this.Info_mqtt = info;
          this.onEetails(info, "火情", true);
        } else if (dataType == 2) {
          // 隐患
          if (info.imei != this.deviceCode_c) return;
          this.Info_mqtt = info;
          this.onEetails(info, "故障", true);
        } else if (dataType == 3) {
          // 反馈
          if (info.deviceCode != this.deviceCode_c) return;
          this.Info_mqtt = info;
          this.onEetails(info, "反馈1");
        } else if (dataType == 4) {
          // if(info.layoutType == 2) {
          //   // 多线盘

          // } else if(info.layoutType == 3) {
          //   // 总线盘

          // }
          if (this.c_hostInfo.deviceCode == info.deviceCode) {
            this.Info_mqtt = info;
          }
        }
      });
    },
    // 获取mqtt信息
    async getMqttInfo() {
      let res = await reqClient(this.user.userId);
      if (res.code !== 20000) return this.$message.error(res.message);
      this.$store.commit("saveMu", res.data.rows.mu);
      this.$store.commit("saveMp", res.data.rows.mp);
      this.$store.commit("saveId", res.data.rows.mc);
    },

    // 字节流转json
    onTransJson(evt) {
      let encodedString = String.fromCodePoint.apply(null, new Uint8Array(evt));
      let decodedString = decodeURIComponent(escape(encodedString)); //没有这一步中文会乱码
      return decodedString;
    },
    // 时间戳转成日期格式： 年-月-日,时-分-秒
    timestampToTime2(timestamp) {
      if (timestamp === 0 || timestamp == null) {
        return "";
      } else {
        // var date = new Date(timestamp * 1000)// 时间戳为10位需*1000，时间戳为13位的话不需乘1000
        var date = new Date(timestamp);
        var Y = date.getFullYear() + "-";
        var M =
          (date.getMonth() + 1 < 10
            ? "0" + (date.getMonth() + 1)
            : date.getMonth() + 1) + "-";
        var D =
          date.getDate() < 10
            ? "0" + date.getDate() + " "
            : date.getDate() + " ";
        var H = date.getHours() + ":";
        var M2 =
          (date.getMinutes() < 10
            ? "0" + date.getMinutes()
            : date.getMinutes()) + ":";
        var S =
          date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
        return Y + M + D + H + M2 + S;
      }
    },

    // 退出
    exit() {
      this.$confirm("确定要退出账号吗?", "温馨提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const res = await reqLogout({ id: this.user.userId });
          sessionStorage.clear();
          this.$router.push("/login");
          window.location.reload(); //页面重新加载一次即可清空vuex
          // onDestory(); // 销毁地图
        })
        .catch(() => {});
    },
  },
};
</script>
  
  <style lang="less" scoped>
@import url("./datav.less");

.fontSize (@px, @attr: font-size) {
  @vw: (@px / 1920) * 100;
  @{attr}: ~"@{vw}vw";
}

// 弹窗
::v-deep .el-drawer.ltr,
.el-drawer.rtl {
  width: 22% !important;
}

::v-deep .el-drawer__body {
  // background: linear-gradient(180deg, #1D3294 1%, rgba(0, 25, 102, 0.52) 45%, #1E336E 100%);
  background: #243d83 !important;
  padding-left: 1.5vw;
  padding-right: 1vw;
  padding-top: 3vh;
  box-sizing: border-box;
}

.title1 {
  color: #fff;
  font-size: 14px;
  opacity: 0.8;
  margin-bottom: 15px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  text-align: right;
}

.qiehuan1 {
  margin-top: 10px;
  margin-bottom: 20px;
  display: flex;
  align-items: center;
  font-size: 12px;
  color: #fff;

  > div {
    padding: 6px 20px;
    border-radius: 30px;
    cursor: pointer;
  }

  > div:last-of-type {
    margin-left: 10px;
  }
}

::v-deep .el-tree {
  background: none;
  color: #fff;
  opacity: 0.8;
  // height: 73vh;
  // height: calc(100%-100px);
  height: calc(100% - 185px);
  overflow: auto;
  font-size: 13px;
}

::v-deep .el-tree-node__content {
  padding: 5px 0;
}

/*  鼠标hover改变背景颜色 */
.el-tree ::v-deep .el-tree-node > .el-tree-node__content:hover {
  color: #fff !important;
  background: #001f5b !important;
}

/*  点击时的样式 */
.el-tree ::v-deep .el-tree-node:focus > .el-tree-node__content {
  background-color: #001f5b !important;
}

.el_input {
  width: 80%;
  border-radius: 5px !important;

  ::v-deep .el-input__inner {
    background: #001f5b !important;
    border: none !important;
    border-radius: 5px !important;
    // height: 32px;
    // margin-top: 4px;
  }
}

::v-deep .el-button--primary {
  background: #003c9b !important;
  border: 1px solid #01def9 !important;
  color: #d1d1d1 !important;
}

// el-tree布局
.custom-tree-node {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: space-between;
  position: relative;
  padding-left: 0.3%;
  box-sizing: border-box;

  .tree-node_ctrls {
    position: absolute;
    right: 0;
    width: 30%;
    text-align: right;
    padding-right: 10px;
  }
}

::v-deep .div_box .el-input__inner {
  background: #001f5b !important;
  border: 1px solid #192a5f !important;
}

::v-deep .el-tree__empty-block {
  height: 86% !important;
}

::v-deep .el-button {
  background-color: transparent !important;
  border-color: #4072b9 !important;
  color: #fff !important;

  &:hover {
    border-color: #568ade !important;
    color: #409eff !important;
  }
}

::v-deep .el-input__inner {
  background-color: transparent !important;
}
.tableBtnIcon {
  color: rgba(2, 220, 249, 0.8);
  font-size: 1.1vw;
  cursor: pointer;
}
::v-deep .el_button.el-button {
  background: transparent !important;
  border: transparent !important;
}
</style>
  